#!/bin/sh
#
#       OCF Resource Agent compliant resource script.
#
# Copyright (c) 2009 IN-telegence GmbH & Co. KG, Dominik Klein
#                    All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it would be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# Further, this software is distributed without any warranty that it is
# free of the rightful claim of any third person regarding infringement
# or the like.  Any license provided herein, whether implied or
# otherwise, applies only to this software file.  Patent licenses, if
# any, provided herein do not apply to combinations of this program with
# other software, or any other product whatsoever.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.

# OCF instance parameters
#       OCF_RESKEY_basedir
#	OCF_RESKEY_pidfile [optional, default=$basedir/logs/nameserver.pid]
#       OCF_RESKEY_user [optional, default=admin]
#       OCF_RESKEY_stop_timeout 
#       OCF_RESKEY_rsip
#       OCF_RESKEY_upsport
#
#
# This RA starts $binfile with $cmdline_options as $user and writes a $pidfile from that. 
# If you want it to, it logs:
# - stdout to $logfile, stderr to $errlogfile or 
# - stdout and stderr to $logfile
# - or to will be captured by lrmd if these options are omitted.
# Monitoring is done through $pidfile or your custom $monitor_hook script. 
# The RA expects the program to keep running "daemon-like" and
# not just quit and exit. So this is NOT (yet - feel free to
# enhance) a way to just run a single one-shot command which just
# does something and then exits.

# Initialization:
. ${OCF_ROOT}/resource.d/heartbeat/.ocf-shellfuncs
. ${OCF_ROOT}/resource.d/heartbeat/.ocf-returncodes

getpid() {
        grep -o '[0-9]*' $1
}

monitor_rootserver() {
	if ! test -x $montool  
	then	
		ocf_log debug "montool $montool doesnot exist"
		return $OCF_ERR_PERM
	fi
	cmd="$montool -i $rsip -p $rsport"
	ocf_log debug "begin to monitor $binfile service with command $cmd"
	eval $cmd
	if [ $? -ne 0 ]
	then
		ocf_log debug "$montool return ERROR"
		return $OCF_ERR_GENERIC
	else
		ocf_log debug "$montool return OK"
		return $OCF_SUCCESS
	fi
}

switch_rootserver() {
#    cmd="$montool -i $rsip -p $rsport -n -s 1"
#    eval $cmd
    echo
}

rootserver_status() {
	if test -f "$pidfile"
	then
		if pid=`getpid $pidfile` && [ "$pid" ] && kill -0 $pid
		then
			#status=`check_nameserver_running_status`
			ocf_log debug "rootserver(pid=$pid) is running"
			return $OCF_RUNNING
		else
			# pidfile w/o process means the process died
			ocf_log debug "rootserver(pid=$pid) is not running"
            return $OCF_NOT_RUNNING
		fi
	else
		ocf_log debug "pidfile $pidfile doesnot exist"
		return $OCF_NOT_RUNNING
	fi
}

rootserver_start() {
	if ! rootserver_status
	then
		if [ -f "$binfile" ]
		then
			cmd="su - $user -c \"$binfile $cmdline_options\""
			#cmd="$binfile $cmdline_options"
		fi
        ocf_log debug "donot Starting $process: $cmd"
		#ocf_log debug "Starting $process: $cmd"
		# Execute the command as created above
		#eval $cmd
		#sleep 1

		if rootserver_status
		then
			ocf_log debug "$process: $cmd started successfully"
            switch_rootserver
			return $OCF_SUCCESS
		else 
			ocf_log err "$process: $cmd could not be started"
			return $OCF_ERR_GENERIC
		fi
	else
		# If already running, consider start successful
		ocf_log debug "$process: $cmd is already running"
        switch_rootserver
		return $OCF_SUCCESS
	fi
}

rootserver_stop() {
        if [ -n "$OCF_RESKEY_stop_timeout" ]
        then
                stop_timeout=$OCF_RESKEY_stop_timeout
        elif [ -n "$OCF_RESKEY_CRM_meta_timeout" ]; then
                # Allow 2/3 of the action timeout for the orderly shutdown
                # (The origin unit is ms, hence the conversion)
                stop_timeout=$((OCF_RESKEY_CRM_meta_timeout/1500))
        else
                stop_timeout=10
        fi

	if rootserver_status
	then
                pid=`getpid $pidfile`
                kill $pid
                return $OCF_SUCCESS
#                i=0
#                while [ $i -lt $stop_timeout ]
#                do
#                        if ! rootserver_status
#                        then
#                        	rm -f $pidfile
#                                return $OCF_SUCCESS
#                        fi
#                        sleep 1 
#                        let "i++"
#                done
#
#                ocf_log warn "Stop with SIGTERM failed/timed out, now sending SIGKILL."
#                kill -9 $pid
#                rm -f $pidfile
#                if ! rootserver_status
#                then
#                        ocf_log warn "SIGKILL did the job."
#                        return $OCF_SUCCESS
#                else
#                        ocf_log err "Failed to stop - even with SIGKILL."
#                        return $OCF_ERR_GENERIC
#                fi
	else
		# was not running, so stop can be considered successful
		ocf_log warn "rootserver not running."
		rm -f $pidfile 
		return $OCF_SUCCESS
	fi
}

rootserver_monitor() {
	rootserver_status
	ret=$?
	if [ $ret -eq $OCF_SUCCESS ]
	then
		OCF_RESKEY_monitor_hook="monitor_rootserver"
		ocf_log debug "rootserver_monitor hook func: $OCF_RESKEY_monitor_hook"
		if [ -n "$OCF_RESKEY_monitor_hook" ]; then
			eval "$OCF_RESKEY_monitor_hook"
                        if [ $? -ne $OCF_SUCCESS ]; then
                                return ${OCF_ERR_GENERIC}
                        fi
			return $OCF_SUCCESS
		else
			true
			ocf_log debug "should not reach here monitor_hook=$OCF_RESKEY_monitor_hook"
		fi
	else
		return $ret
	fi
}

# FIXME: Attributes special meaning to the resource id
process="$OCF_RESOURCE_INSTANCE"
binfile="$OCF_RESKEY_basedir/rootserver"
cmdline_options=""
pidfile="$OCF_RESKEY_pidfile"
[ -z "$pidfile" ] && pidfile="$OCF_RESKEY_basedir/log/root.pid"

user="$OCF_RESKEY_user"
[ -z "$user" ] && user=admin

### monitor namserver parameters ########
rsip="$OCF_RESKEY_rsip"
rsport="$OCF_RESKEY_rsport"
montool="$OCF_RESKEY_montool"
[ -z "$montool" ] && montool="$OCF_RESKEY_basedir/ups_mon"

## FIXME: Attributes special meaning to the resource id
#process="rootserver"
#binfile="./rootserver"
#cmdline_options=""
#pidfile="./rootserver.pid"
##[ -z "$pidfile" ] && pidfile="$OCF_RESKEY_basedir/logs/nameserver.pid"
#
#user="yanran.hfs"
##[ -z "$user" ] && user=admin
#
#### monitor namserver parameters ########
#rsip="10.232.36.43"
#rsport="11030"
#montool="./ups_mon"
##[ -z "$montool" ] && montool="$OCF_RESKEY_basedir/lib/nshamon"

rootserver_validate() {
	if ! su - $user -c "test -x $binfile"
	then
		ocf_log err "binfile $binfile does not exist or is not executable by $user."
		exit $OCF_ERR_INSTALLED
	fi
	if ! getent passwd $user >/dev/null 2>&1
	then
		ocf_log err "user $user does not exist."
		exit $OCF_ERR_INSTALLED
	fi
	return $OCF_SUCCESS
}

rootserver_meta() {
cat <<END
<?xml version="1.0"?>
<!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">
<resource-agent name="rootserver">
<version>1.0</version>
<longdesc lang="en">
This is a OCF RA to manage ob ha rootserver.
</longdesc>
<shortdesc lang="en">Manages an ob rootserver service</shortdesc>

<parameters>
<parameter name="basedir" required="1" unique="1">
<longdesc lang="en">nameserver root directory </longdesc>
<shortdesc lang="en">Full path name of the binary to be executed</shortdesc>
<content type="string"/>
</parameter>
<parameter name="pidfile" required="0">
<longdesc lang="en">
File to read/write the PID from/to.
</longdesc>
<shortdesc lang="en">File to write STDOUT to</shortdesc>
<content type="string"/>
</parameter>
<parameter name="user" required="0">
<longdesc lang="en">
User to run the command as
</longdesc>
<shortdesc lang="en">User to run the command as</shortdesc>
<content type="string" default="admin"/>
</parameter>
<parameter name="stop_timeout">
<longdesc lang="en">
In the stop operation: Seconds to wait for kill -TERM to succeed
before sending kill -SIGKILL. Defaults to 2/3 of the stop operation timeout.
</longdesc>
<shortdesc lang="en">Seconds to wait after having sent SIGTERM before sending SIGKILL in stop operation</shortdesc>
<content type="string" default=""/>
</parameter>
<parameter name="rsip">
<longdesc lang="en"> nameserver ipaddr or hostname </longdesc>
<shortdesc lang="en">nameserver ipaddr or hostname </shortdesc>
<content type="string" default="localhost"/>
</parameter>
<parameter name="rsport">
<longdesc lang="en"> rootserver port </longdesc>
<shortdesc lang="en"> rootserver port </shortdesc>
<content type="integer" default="3100"/>
</parameter>
<parameter name="montool">
<longdesc lang="en"> check updateerver if working well, run as -i ip -p port </longdesc>
<shortdesc lang="en"> check rootserver status </shortdesc>
<content type="string"/>
</parameter>
</parameters>
<actions>
<action name="start"   timeout="600" />
<action name="stop"    timeout="30" />
<action name="monitor" depth="0"  timeout="20" interval="5" />
<action name="meta-data"  timeout="5" />
<action name="validate-all"  timeout="5" />
</actions>
</resource-agent>
END
exit 0
}

case "$1" in
	meta-data|metadata|meta_data)
		rootserver_meta
	;;
	start)
		rootserver_start
	;;
	stop)
		rootserver_stop
	;;
	monitor)
		rootserver_monitor
	;;
	validate-all)
		rootserver_validate
	;;
	*)
		ocf_log err "$0 was called with unsupported arguments: $*"
		exit $OCF_ERR_UNIMPLEMENTED
	;;
esac
